<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\MessageTemplate;
use think\facade\Db;
use think\Request;
use think\facade\Log;
use app\validate\MessageTemplateValidate;

class MessageTemplateController extends BaseController
{
    /**
     * 获取消息模板列表
     */
    public function list(Request $request)
    {
        try {
            $merchant_id = $request->param('merchant_id', 0);
            $message_setting_id = $request->param('message_setting_id', 0);
            $message_type = $request->param('message_type', 0);

            $where = [];
            if ($merchant_id) {
                $where[] = ['merchant_id', '=', $merchant_id];
            }
            if ($message_setting_id) {
                $where[] = ['message_setting_id', '=', $message_setting_id];
            }
            if ($message_type) {
                $where[] = ['message_type', '=', $message_type];
            }

            $list = MessageTemplate::where($where)
                ->order('id', 'desc')
                ->select();

            foreach ($list as &$item) {
                $item['type_text'] = $this->getTypeText($item['type']);
                $item['status_text'] = $item['status'] == 1 ? '正常' : '禁用';
                // 添加消息配置信息
                if ($item['messageSetting']) {
                    $item['type_text'] = $item['messageSetting']->getTypeTextAttr();
                    $item['scene_text'] = $item['messageSetting']->getSceneTextAttr();
                }
            }

            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
   /**
    * 添加模板
    * @param \think\Request $request
    * @return void
    */
   public function add(Request $request)
   {
       Db::startTrans();
       try {
           $data = $request->post();
           
           // 数据验证
           $validate = new MessageTemplateValidate();
           if (!$validate->scene('add')->check($data)) {
               return $this->error($validate->getError());
           }

           // 检查模板ID是否重复
           $exists = MessageTemplate::where([
               'type' => $data['type'],
               'template_code' => $data['template_code']
           ])->find();
           
           if ($exists) {
               return $this->error('该类型下模板ID已存在');
           }

           // 创建模板
           $template = new MessageTemplate();
           $template->save([
               'scene' => $data['scene'],
               'template_name' => $data['template_name'],
               'type' => $data['type'],
               'template_code' => $data['template_code'],
               'template_content' => $data['template_content'],
               'status' => $data['status'],
               'create_time' => date('Y-m-d H:i:s'),
               'update_time' => date('Y-m-d H:i:s')
           ]);

           Db::commit();
           return $this->success('添加成功');
       } catch (\Exception $e) {
           Db::rollback();
           Log::error('添加消息模板失败: '.$e->getMessage());
           return $this->error('添加失败: '.$e->getMessage());
       }
   }


    /**
     * 更新消息模板
     */
    public function update(Request $request, $id)
    {
        Db::startTrans();
        try {
            $data = $request->post();
            
            // 验证数据
            $validate = new \app\validate\MessageTemplateValidate();
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }

            $template = MessageTemplateConfig::find($id);
            if (!$template) {
                return json(['code' => 1, 'msg' => '消息模板不存在']);
            }

            $template->save([
                'template_name' => $data['template_name'],
                'template_content' => $data['template_content'],
                'status' => $data['status']
            ]);

            Db::commit();
            return json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取消息类型文本
     */
    private function getTypeText($type)
    {
        $types = [
            1 => '公众号消息',
            2 => '微信小程序',
            3 => '短信'
        ];
        return $types[$type] ?? '未知';
    }
} 